package com.thinksns.sociax.t4.android.api;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.constant.AppConstant;
import com.thinksns.sociax.net.Request;
import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.model.ModelBackMessage;
import com.thinksns.sociax.t4.model.ModelWeibo;
import com.thinksns.sociax.t4.sharesdk.ShareSDKManager;
import com.thinksns.sociax.thinksnsbase.base.BaseApplication;
import com.thinksns.tschat.chat.TSChatManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微博视频上传进度监听类
 */
public class FileUploadAsyncTask extends AsyncTask<File, Integer, String> {

    private Uri.Builder uri;
    private Context context;
    private long totalSize;
    private Notification notification;
    private NotificationManager notiManager;
    private Map<String, String> mParams;
    int percent = 0;

    public static boolean isInUpload;
    private String mResult;
    private OnPostExecuteListener mOnPostExecuteListener;

    public FileUploadAsyncTask(Context context, Uri.Builder uri, Map mParams) {
        this.context = context;
        this.uri = uri;
        this.mParams = mParams;
        initNotifycation();
    }

    public void setOnPostExecuteListener(OnPostExecuteListener onPostExecuteListener) {
        mOnPostExecuteListener = onPostExecuteListener;
    }

    /**
     * 更新进度条
     */
    public void initNotifycation() {
        notiManager = (NotificationManager) Thinksns
                .getContext().getSystemService(
                        Activity.NOTIFICATION_SERVICE);
        notification = new Notification();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.icon = R.drawable.app_load;
        notification.tickerText = "正在上传视频";
        notification.contentView = new RemoteViews(Thinksns.getContext()
                .getPackageName(), R.layout.video_progress_item);

        notiManager.notify(0, notification);
    }

    @Override
    protected void onPreExecute() {
        isInUpload = true;
    }

    @Override
    public String doInBackground(File... params) {
        // 保存需上传文件信息
        MultipartEntityBuilder entitys = MultipartEntityBuilder.create();
        entitys.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entitys.setCharset(Charset.forName(HTTP.UTF_8));
        if (params[0] != null) {
            entitys.addPart("video", new FileBody(params[0]));
        }
        if (params.length > 1)
            entitys.addPart("pic", new FileBody(params[1]));
        for (String key : mParams.keySet()) {
            uri.appendQueryParameter(key, mParams.get(key));
        }

        HttpEntity httpEntity = entitys.build();
        totalSize = httpEntity.getContentLength();

        ProgressOutHttpEntity progressHttpEntity = new ProgressOutHttpEntity(
                httpEntity, new ProgressListener() {
            @Override
            public void transferred(long transferedBytes) {
                if (transferedBytes * 100 / totalSize >= percent + 1) {
                    publishProgress((int) (100 * transferedBytes / totalSize));
                    percent++;
                }
            }
        });
        return uploadFile(uri.toString(), progressHttpEntity);
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
//        pd.setProgress((int) (progress[0]));

        notification.contentView.setTextViewText(
                R.id.content_view_text1, progress[0] + "%");
        notification.contentView.setProgressBar(
                R.id.content_view_progress, 100,
                progress[0], false);
        notiManager.notify(0, notification);
    }

    @Override
    protected void onPostExecute(String result) {
        isInUpload = false;
        ModelBackMessage backMessage = new ModelBackMessage(result);
        if (backMessage.getStatus() == AppConstant.API_AUTH_FAIL) {
            // 断开 socket
            TSChatManager.close();
            // 注销极光推送
            ShareSDKManager.unregister();
            Activity lastActivity = BaseApplication.getLastActivity();
            if (lastActivity instanceof ThinksnsAbscractActivity) {
                ((ThinksnsAbscractActivity) lastActivity).reLogin();
            }
        }
        if (mOnPostExecuteListener != null) {
            mOnPostExecuteListener.onPostExecute(result);
        }

    }

    /**
     * 上传文件到服务器
     *
     * @param url    服务器地址
     * @param entity 文件
     * @return
     */
    public String uploadFile(String url, ProgressOutHttpEntity entity) {
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        // 设置连接超时时间
        httpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        InputStream inputStream;
        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                int ch;
                StringBuilder sb2 = new StringBuilder();
                while ((ch = inputStream.read()) != -1) {
                    sb2.append((char) ch);
                }
                mResult = sb2.toString();
                return mResult;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null && httpClient.getConnectionManager() != null) {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return null;
    }


    public interface OnPostExecuteListener {
        void onPostExecute(String result);
    }
}
